import { defineStore } from 'pinia'
import { messageApi } from '@/api/message'
import { ElMessage } from 'element-plus'

export const useMessageStore = defineStore('message', {
  state: () => ({
    // 帖子列表数据
    messages: [],
    // 当前选中的帖子
    currentMessage: null,
    // 当前帖子的回复列表
    currentReplies: [],
    // 加载状态
    loading: false,
    repliesLoading: false,
    // 分页状态
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0
    },
    // 回复分页状态
    repliesPagination: {
      current: 1,
      pageSize: 20,
      total: 0
    },
    // 搜索和筛选条件
    searchParams: {
      keyword: '', // 搜索关键词（标题或作者）
      status: '', // 状态筛选
      author: '', // 作者筛选
      dateRange: [], // 发布时间范围
      tags: [] // 标签筛选
    },
    // 批量操作选中的帖子ID
    selectedMessageIds: []
  }),

  getters: {
    // 获取待审核帖子
    pendingMessages: (state) => state.messages.filter(msg => msg.status === 'pending'),
    
    // 获取已批准帖子
    approvedMessages: (state) => state.messages.filter(msg => msg.status === 'approved'),
    
    // 获取已拒绝帖子
    rejectedMessages: (state) => state.messages.filter(msg => msg.status === 'rejected'),
    
    // 获取热门帖子（回复数较多）
    popularMessages: (state) => {
      return [...state.messages]
        .filter(msg => msg.status === 'approved')
        .sort((a, b) => (b.replyCount || 0) - (a.replyCount || 0))
        .slice(0, 10)
    },
    
    // 帖子统计信息
    messageStats: (state) => {
      const stats = {
        total: state.messages.length,
        pending: 0,
        approved: 0,
        rejected: 0,
        totalReplies: 0
      }
      
      state.messages.forEach(msg => {
        stats[msg.status] = (stats[msg.status] || 0) + 1
        stats.totalReplies += msg.replyCount || 0
      })
      
      return stats
    },
    
    // 获取所有标签
    allTags: (state) => {
      const tags = new Set()
      state.messages.forEach(msg => {
        if (msg.tags && Array.isArray(msg.tags)) {
          msg.tags.forEach(tag => tags.add(tag))
        }
      })
      return Array.from(tags)
    }
  },

  actions: {
    // 获取帖子列表
    async fetchMessages(params = {}) {
      this.loading = true
      try {
        const queryParams = {
          page: this.pagination.current,
          pageSize: this.pagination.pageSize,
          ...this.searchParams,
          ...params
        }
        
        const response = await messageApi.getMessages(queryParams)
        this.messages = response.data || []
        this.pagination.total = response.total || 0
        
        return response
      } catch (error) {
        console.error('获取帖子列表失败:', error)
        ElMessage.error('获取帖子列表失败')
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取帖子详情
    async fetchMessageDetail(id) {
      try {
        const response = await messageApi.getMessageDetail(id)
        this.currentMessage = response.data
        return response
      } catch (error) {
        console.error('获取帖子详情失败:', error)
        ElMessage.error('获取帖子详情失败')
        throw error
      }
    },

    // 获取帖子回复列表
    async fetchMessageReplies(messageId, params = {}) {
      this.repliesLoading = true
      try {
        const queryParams = {
          page: this.repliesPagination.current,
          pageSize: this.repliesPagination.pageSize,
          ...params
        }
        
        const response = await messageApi.getMessageReplies(messageId, queryParams)
        this.currentReplies = response.data || []
        this.repliesPagination.total = response.total || 0
        
        return response
      } catch (error) {
        console.error('获取回复列表失败:', error)
        ElMessage.error('获取回复列表失败')
        throw error
      } finally {
        this.repliesLoading = false
      }
    },

    // 审核帖子（批准）
    async approveMessage(id) {
      try {
        await messageApi.approveMessage(id)
        
        // 更新本地帖子状态
        const index = this.messages.findIndex(msg => msg.id === id)
        if (index !== -1) {
          this.messages[index].status = 'approved'
        }
        
        ElMessage.success('帖子已批准')
      } catch (error) {
        console.error('批准帖子失败:', error)
        ElMessage.error('批准帖子失败')
        throw error
      }
    },

    // 审核帖子（拒绝）
    async rejectMessage(id, reason = '') {
      try {
        await messageApi.rejectMessage(id, { reason })
        
        // 更新本地帖子状态
        const index = this.messages.findIndex(msg => msg.id === id)
        if (index !== -1) {
          this.messages[index].status = 'rejected'
        }
        
        ElMessage.success('帖子已拒绝')
      } catch (error) {
        console.error('拒绝帖子失败:', error)
        ElMessage.error('拒绝帖子失败')
        throw error
      }
    },

    // 删除帖子
    async deleteMessage(id) {
      try {
        await messageApi.deleteMessage(id)
        
        // 从本地数据中移除帖子
        this.messages = this.messages.filter(msg => msg.id !== id)
        this.pagination.total -= 1
        
        ElMessage.success('帖子删除成功')
      } catch (error) {
        console.error('删除帖子失败:', error)
        ElMessage.error('删除帖子失败')
        throw error
      }
    },

    // 删除回复
    async deleteReply(replyId, messageId) {
      try {
        await messageApi.deleteReply(replyId)
        
        // 从本地回复数据中移除
        this.currentReplies = this.currentReplies.filter(reply => reply.id !== replyId)
        this.repliesPagination.total -= 1
        
        // 更新帖子的回复数
        const messageIndex = this.messages.findIndex(msg => msg.id === messageId)
        if (messageIndex !== -1) {
          this.messages[messageIndex].replyCount = Math.max(0, (this.messages[messageIndex].replyCount || 1) - 1)
        }
        
        ElMessage.success('回复删除成功')
      } catch (error) {
        console.error('删除回复失败:', error)
        ElMessage.error('删除回复失败')
        throw error
      }
    },

    // 批量审核帖子
    async batchApproveMessages(messageIds) {
      try {
        await messageApi.batchApproveMessages(messageIds)
        
        // 更新本地帖子状态
        messageIds.forEach(id => {
          const index = this.messages.findIndex(msg => msg.id === id)
          if (index !== -1) {
            this.messages[index].status = 'approved'
          }
        })
        
        ElMessage.success(`成功批准 ${messageIds.length} 个帖子`)
      } catch (error) {
        console.error('批量批准帖子失败:', error)
        ElMessage.error('批量批准帖子失败')
        throw error
      }
    },

    // 批量拒绝帖子
    async batchRejectMessages(messageIds, reason = '') {
      try {
        await messageApi.batchRejectMessages(messageIds, { reason })
        
        // 更新本地帖子状态
        messageIds.forEach(id => {
          const index = this.messages.findIndex(msg => msg.id === id)
          if (index !== -1) {
            this.messages[index].status = 'rejected'
          }
        })
        
        ElMessage.success(`成功拒绝 ${messageIds.length} 个帖子`)
      } catch (error) {
        console.error('批量拒绝帖子失败:', error)
        ElMessage.error('批量拒绝帖子失败')
        throw error
      }
    },

    // 批量删除帖子
    async batchDeleteMessages(messageIds) {
      try {
        await messageApi.batchDeleteMessages(messageIds)
        
        // 从本地数据中移除帖子
        this.messages = this.messages.filter(msg => !messageIds.includes(msg.id))
        this.pagination.total -= messageIds.length
        
        ElMessage.success(`成功删除 ${messageIds.length} 个帖子`)
      } catch (error) {
        console.error('批量删除帖子失败:', error)
        ElMessage.error('批量删除帖子失败')
        throw error
      }
    },

    // 搜索帖子
    async searchMessages(keyword) {
      this.searchParams.keyword = keyword
      this.pagination.current = 1
      await this.fetchMessages()
    },

    // 按状态筛选帖子
    async filterByStatus(status) {
      this.searchParams.status = status
      this.pagination.current = 1
      await this.fetchMessages()
    },

    // 按作者筛选帖子
    async filterByAuthor(author) {
      this.searchParams.author = author
      this.pagination.current = 1
      await this.fetchMessages()
    },

    // 按时间范围筛选帖子
    async filterByDateRange(dateRange) {
      this.searchParams.dateRange = dateRange
      this.pagination.current = 1
      await this.fetchMessages()
    },

    // 按标签筛选帖子
    async filterByTags(tags) {
      this.searchParams.tags = tags
      this.pagination.current = 1
      await this.fetchMessages()
    },

    // 综合筛选帖子
    async filterMessages(filters) {
      this.searchParams = { ...this.searchParams, ...filters }
      this.pagination.current = 1
      await this.fetchMessages()
    },

    // 重置搜索和筛选条件
    resetSearchParams() {
      this.searchParams = {
        keyword: '',
        status: '',
        author: '',
        dateRange: [],
        tags: []
      }
    },

    // 设置分页参数
    setPagination(pagination) {
      this.pagination = { ...this.pagination, ...pagination }
    },

    // 设置回复分页参数
    setRepliesPagination(pagination) {
      this.repliesPagination = { ...this.repliesPagination, ...pagination }
    },

    // 设置当前帖子
    setCurrentMessage(message) {
      this.currentMessage = message
    },

    // 清空当前帖子
    clearCurrentMessage() {
      this.currentMessage = null
      this.currentReplies = []
    },

    // 设置选中的帖子ID（用于批量操作）
    setSelectedMessageIds(ids) {
      this.selectedMessageIds = ids
    },

    // 添加选中的帖子ID
    addSelectedMessageId(id) {
      if (!this.selectedMessageIds.includes(id)) {
        this.selectedMessageIds.push(id)
      }
    },

    // 移除选中的帖子ID
    removeSelectedMessageId(id) {
      this.selectedMessageIds = this.selectedMessageIds.filter(selectedId => selectedId !== id)
    },

    // 清空选中的帖子ID
    clearSelectedMessageIds() {
      this.selectedMessageIds = []
    }
  }
})